<template>
	<xn-form-container title="供应商" :width="550" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<!-- 基本信息 -->
			<a-form-item label="供应商名称" name="supplierName">
				<a-input v-model:value="formData.supplierName" placeholder="请输入供应商名称" allow-clear />
			</a-form-item>
			<a-form-item label="供应商编码" name="supplierCode">
				<a-input v-model:value="formData.supplierCode" placeholder="请输入供应商编码" allow-clear />
			</a-form-item>
			<a-form-item label="供应商联系人" name="supplierContact">
				<a-input v-model:value="formData.supplierContact" placeholder="请输入供应商联系人" allow-clear />
			</a-form-item>
			<a-form-item label="计费方式" name="billingMethod">
				<a-input v-model:value="formData.billingMethod" placeholder="请输入计费方式" allow-clear />
			</a-form-item>
			<!-- 短信签名 -->
			<a-divider>短信签名</a-divider>
			<div v-for="(item, index) in formData.sign" :key="item.key">
				<a-space style="display: flex; align-items: center" align="baseline">
					<a-form-item :name="['sign', index, 'signCode']" style="flex: 1; margin-bottom: 0">
						<a-input v-model:value="item.signCode" placeholder="输入短信签名编码" />
					</a-form-item>
					<a-form-item :name="['sign', index, 'signContent']" style="flex: 1; margin-bottom: 0">
						<a-input v-model:value="item.signContent" placeholder="输入短信签名内容" />
					</a-form-item>
					<minus-circle-outlined
						v-if="formData.sign.length > 1"
						@click="removeSign(index)"
						style="color: #ff4d4f; cursor: pointer"
					/>
				</a-space>
			</div>
			<a-form-item>
				<a-button type="dashed" @click="addSign" block>
					<plus-outlined />
					添加签名
				</a-button>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>
<script setup>
	import { ref, reactive } from 'vue'
	import { required } from '@/utils/formRules'
	import { message } from 'ant-design-vue'
	import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons-vue'
	import supplierApi from '@/api/tjzy/supplier/supplierApi'

	// 组件状态
	const visible = ref(false)
	const formRef = ref()
	const submitLoading = ref(false)
	const emit = defineEmits(['successful'])

	// 表单初始数据
	const initFormData = () => ({
		supplierName: '',
		supplierCode: '',
		supplierContact: '',
		billingMethod: '',
		sign: [
			{
				signCode: '',
				signContent: '',
				key: Date.now()
			}
		]
	})

	// 表单数据
	const formData = reactive(initFormData())

	// 表单验证规则
	const formRules = reactive({
		supplierName: [required('请输入供应商名称')],
		supplierCode: [required('请输入供应商编码')],
		supplierContact: [required('请输入供应商联系人')],
		billingMethod: [required('请输入计费方式')]
	})

	// 签名验证规则
	const signRules = reactive({
		signCode: [required('请输入签名编码')],
		signContent: [required('请输入签名内容')]
	})

	// 打开表单
	const onOpen = (record) => {
		visible.value = true
		Object.assign(formData, initFormData())

		if (record) {
			// 处理传入的数据
			const { sign, ...rest } = record
			Object.assign(formData, rest)

			// 处理签名数据
			if (sign) {
				try {
					formData.sign =
						typeof sign === 'string'
							? JSON.parse(sign).map((item) => ({ ...item, key: Date.now() }))
							: sign.map((item) => ({ ...item, key: Date.now() }))
				} catch (e) {
					console.error('解析签名数据失败:', e)
					formData.sign = [
						{
							signCode: '',
							signContent: '',
							key: Date.now()
						}
					]
				}
			}
		}
	}

	// 关闭表单
	const onClose = () => {
		formRef.value?.resetFields()
		visible.value = false
	}

	// 添加签名
	const addSign = () => {
		formData.sign.push({
			signCode: '',
			signContent: '',
			key: Date.now()
		})
	}

	// 移除签名
	const removeSign = (index) => {
		if (formData.sign.length > 1) {
			formData.sign.splice(index, 1)
		} else {
			message.warning('至少需要保留一条签名')
		}
	}

	// 提交表单
	const onSubmit = async () => {
		try {
			// 验证表单
			await formRef.value.validate()
			submitLoading.value = true

			// 准备提交数据
			const submitData = {
				...formData,
				sign: JSON.stringify(
					formData.sign.map((item) => ({
						signCode: item.signCode,
						signContent: item.signContent
					}))
				)
			}

			// 调用API
			await supplierApi.addOrEdit(submitData)
			message.success('保存成功')
			emit('successful')
			onClose()
		} catch (error) {
			console.error('保存失败:', error)
			if (error?.response?.data?.message) {
				message.error(error.response.data.message)
			} else if (error.message) {
				message.error(error.message)
			}
		} finally {
			submitLoading.value = false
		}
	}

	// 暴露方法
	defineExpose({ onOpen })
</script>
